package com.sgcc.fj.pmos.e_fj_mall.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.flyco.tablayout.SlidingTabLayout;
import com.lxj.xpopup.XPopup;
import com.sgcc.fj.pmos.arouter.mall.MallArouterPath;
import com.sgcc.fj.pmos.common.adapter.HomeTabPagerAdapter;
import com.sgcc.fj.pmos.common.base.MvpBaseActivity;
import com.sgcc.fj.pmos.common.bean.BaseResponse;
import com.sgcc.fj.pmos.common.dialog.PackageDetails1PopView;
import com.sgcc.fj.pmos.common.dialog.StoreDetailsPopView;
import com.sgcc.fj.pmos.common.http.HttpInterConst;
import com.sgcc.fj.pmos.common.utils.BigDecimalUtils;
import com.sgcc.fj.pmos.common.utils.DateUtils;
import com.sgcc.fj.pmos.common.utils.ImmersionBarUtils;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.fj.pmos.common.utils.UserManager;
import com.sgcc.fj.pmos.e_fj_mall.bean.MonthEnergyBean;
import com.sgcc.fj.pmos.e_fj_mall.bean.StoreHomeBean;
import com.sgcc.fj.pmos.e_fj_mall.bean.StoreYearBean;
import com.sgcc.fj.pmos.e_fj_mall.contract.StoreHomePageContract;
import com.sgcc.fj.pmos.e_fj_mall.fragment.AllGoodsFragment;
import com.sgcc.fj.pmos.e_fj_mall.fragment.RecommendCommoditiesFragment;
import com.sgcc.fj.pmos.e_fj_mall.presenter.StoreHomePagePresenter;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 店铺首页
 */
@Route(path = MallArouterPath.MALL_STOREHOMEPAGE)
public class StoreHomePageActivity extends MvpBaseActivity<StoreHomePagePresenter> implements StoreHomePageContract.View {

    private ImageView mIvBack;
    private RelativeLayout mLayoutRight;
    private SlidingTabLayout mStlContent;
    private ViewPager mViewpager;

    private RelativeLayout mRlFocus;
    private ImageView mIvFocus;
    private TextView mTvFocus;
    private TextView tvEntName;

    private ImageView mIvCompanyLogo;
    private TextView mTvEntName;
    private TextView mTvGray;
    private TextView mTvLeft;
    private TextView mTvCenter;
    private TextView mTvRight;
    private TextView tv_month1;
    private TextView tv_month2;

    private TextView month_txt;
    private TextView year_txt;

    private LinearLayout month_liner;
    private LinearLayout year_liner;

    private List<Fragment> fragments = new ArrayList<>();
    private HomeTabPagerAdapter homeTabPagerAdapter;
    private StoreHomeBean.RowsBean mBean;

    private RelativeLayout rela_search;
    TimePickerView pvTimeYear, pvTimeMonth;
    Calendar startDate = Calendar.getInstance();
    Calendar endDate = Calendar.getInstance();
    @Autowired
    public String membersSdId;

    RelativeLayout re_store_name;
    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_storehomepage_fj;
    }

    @Override
    protected StoreHomePagePresenter createPresenter() {
        return new StoreHomePagePresenter();
    }

    @Override
    protected void initViews() {
        super.initViews();
        ImmersionBarUtils.initColorBaseBar(this, R.color.white);
        findViewByIds();
        mPresenter.getStoreDetails(membersSdId);
    }

    private void findViewByIds() {
        month_txt = findViewById(R.id.month_txt);
        year_txt = findViewById(R.id.year_txt);
        month_liner = findViewById(R.id.month_liner);
        year_liner = findViewById(R.id.year_liner);
        year_liner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (pvTimeYear != null) {
                    pvTimeYear.show();
                }

            }
        });

        month_liner.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (pvTimeMonth != null) {
                    String time = month_txt.getText().toString();
                    if(!TextUtils.isEmpty(time)){
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
                        try {
                            Date newTime = format.parse(time);
                            Calendar calendar1=    Calendar.getInstance();
                            calendar1.setTime(newTime);
                            pvTimeMonth.setDate(calendar1);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    pvTimeMonth.show();
                }
            }
        });
        re_store_name= findViewById(R.id.re_store_name);
        re_store_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mBean!=null){
                    new XPopup.Builder(ActivityUtils.getTopActivity())
                            .dismissOnTouchOutside(true)
                            .asCustom(new StoreDetailsPopView(ActivityUtils.getTopActivity(),mBean))
                            .show();
                }
            }
        });
        mIvBack = (ImageView) findViewById(R.id.ivBack);
        mLayoutRight = (RelativeLayout) findViewById(R.id.layoutRight);
        mRlFocus = (RelativeLayout) findViewById(R.id.rl_focus);
        mIvFocus = (ImageView) findViewById(R.id.iv_focus);
        mTvFocus = (TextView) findViewById(R.id.tv_focus);
        tvEntName = (TextView) findViewById(R.id.tv_entName);
        mStlContent = (SlidingTabLayout) findViewById(R.id.stl_content);
        mViewpager = (ViewPager) findViewById(R.id.viewpager);
        mIvCompanyLogo = (ImageView) findViewById(R.id.iv_company_logo);
        mTvGray = (TextView) findViewById(R.id.tv_gray);
        mTvLeft = (TextView) findViewById(R.id.tv_left);
        mTvCenter = (TextView) findViewById(R.id.tv_center);
        mTvRight = (TextView) findViewById(R.id.tv_right);
        tv_month1 = (TextView) findViewById(R.id.tv_month1);
        tv_month2 = (TextView) findViewById(R.id.tv_month2);
        rela_search = (RelativeLayout) findViewById(R.id.rela_search);
        String[] titleList = getResources().getStringArray(R.array.store_home_page_title);

        RecommendCommoditiesFragment recommendCommoditiesFragment = new RecommendCommoditiesFragment();
        Bundle left_bundle = new Bundle();
        left_bundle.putString("membersSdId", membersSdId);
        recommendCommoditiesFragment.setArguments(left_bundle);


        AllGoodsFragment allGoodsFragment = new AllGoodsFragment();
        Bundle right_bundle = new Bundle();
        right_bundle.putString("membersSdId", membersSdId);
        allGoodsFragment.setArguments(right_bundle);

        fragments.add(recommendCommoditiesFragment);
        fragments.add(allGoodsFragment);
        homeTabPagerAdapter = new HomeTabPagerAdapter(getSupportFragmentManager(), fragments);
        homeTabPagerAdapter.setmBottomTabNames(titleList);
        mViewpager.setOffscreenPageLimit(2);
        mViewpager.setAdapter(homeTabPagerAdapter);
        mStlContent.setViewPager(mViewpager);
        mViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        mLayoutRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goMainActivity();
            }
        });


        mRlFocus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserManager.toLogin()) {
                    if ("00".equals(mBean.getUstatus())) {//收藏状态： 0未收藏 01 已收藏
                        mPresenter.addUserPackageCollection(mBean.getMembersUserName(), mBean.getMembersSdId(), mBean.getMembersSdName());
                    } else {
                        mPresenter.deletePackageById(mBean.getMembersSdId());
                    }
                }
            }
        });
        rela_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance()
                        .build(MallArouterPath.MALL_SEARCH)
                        .withInt("searchType", 1)
                        .navigation();
            }
        });

//        tvEntName.setOnClickListener(view -> DialogUtil.showEnterpriseDetailDialog(this));
    }

    @Override
    public void querySuccess(StoreHomeBean response) {
        if (response != null) {
            if ("200".equals(response.getCode())) {
                if (response.getRows() != null) {
                    if (!response.getRows().isEmpty()) {
                        mBean = response.getRows().get(0);

                        String img_url = HttpInterConst.BASEURL_IMG +
                                (TextUtils.isEmpty(mBean.getShopFileId()) ? mBean.getFileId() : mBean.getShopFileId());
                        Glide.with(mContext).load(img_url).placeholder(R.mipmap.deft_merchant).error(R.mipmap.deft_merchant).into(mIvCompanyLogo);

                        tvEntName.setText(mBean.getMembersSdName());
                        mTvGray.setText("已售--件 | --人关注");
                        mTvRight.setText(TextUtils.isEmpty(mBean.getCreditRating()) ? "——" : mBean.getCreditRating());

                        String saleEnergy = BigDecimalUtils.onKeep3Decimal(mBean.getSaleEnergy());
                        BigDecimal kysEnergy_b = new BigDecimal(saleEnergy);
                        int i = kysEnergy_b.compareTo(BigDecimal.ZERO);
                        String result = "";
                        if (i == -1) {
                            result = "不限量";
                        } else {
                            result = saleEnergy;
                        }

                        mTvLeft.setText(result);
                        mTvCenter.setText(BigDecimalUtils.onKeep3Decimal(mBean.getYearSaleEnergy()));

//                        tv_month1.setText(BigDecimalUtils.onKeep3Decimal(mBean.getMonthkxsdl()));
//
//                        tv_month2.setText(BigDecimalUtils.onKeep3Decimal(mBean.getMonthyxsdl()));
//

                        if ("00".equals(mBean.getUstatus())) {//收藏状态： 0未收藏 01 已收藏
                            mRlFocus.setBackgroundResource(R.drawable.bg_storehome_top);
                            mIvFocus.setBackgroundResource(R.mipmap.storehome_top);
                            mTvFocus.setTextColor(Color.parseColor("#FF078FFB"));
                        } else {
                            mRlFocus.setBackgroundResource(R.drawable.bg_storehome_toped);
                            mIvFocus.setBackgroundResource(R.mipmap.storehome_toped);
                            mTvFocus.setTextColor(Color.parseColor("#ffffff"));
                        }
//                        mPresenter.queryMonthEnergy(mBean.getMembersSdId(),mBean.getYearMonth().replace("年","").replace("月",""));
                    }
                }


                year_txt.setText(mBean.getYear());
                month_txt.setText(getGangTime(mBean.getYearMonth()));
                mPresenter.queryMonthEnergy(mBean.getMembersSdId(), getGangTime(mBean.getYearMonth()).replace("-",""));
                mPresenter.queryYear(mBean.getMembersSdId(), mBean.getYear());
                initYearSelecter();
                initMonthSelecter(getGangTime(mBean.getYearMonth()));
            }
        }
    }

    @Override
    public void queryFailed() {

    }

    private String getGangTime(String month) {
        if (!TextUtils.isEmpty(month)) {
            String month1 = month.replace("月", "");

            if (month1.contains("年")) {
                String[] monthlist = month1.split("年");
                String monthFinal = "";
                int monthNum = Integer.valueOf(monthlist[1]);
                if (monthNum < 10) {
                    monthFinal = "0" + monthNum;
                }
                return monthlist[0] + "-" + monthFinal;
            } else {
                ToastUtils.showShort("默认返回月份有误");
                return "";
            }
        } else {
            ToastUtils.showShort("默认月份为空");
            return "";
        }

    }

    @Override
    public void addCollectionSuccess(BaseResponse response) {
        if (response != null) {
            if (response.isSuccess()) {
                mPresenter.getStoreDetails(membersSdId);
            }
        }
    }

    @Override
    public void addCollectionFailed() {

    }

    @Override
    public void delCollectionSuccess(BaseResponse response) {
        if (response != null) {
            if (response.isSuccess()) {
                mPresenter.getStoreDetails(membersSdId);
            }
        }
    }

    @Override
    public void delCollectionFailed() {

    }

    @Override
    public void queryMonthEnergySuccess(MonthEnergyBean response) {
        if (response != null) {
            if (response.getCode() == 200) {
                tv_month1.setText(BigDecimalUtils.onKeep3Decimal(response.getData().getMonthkxsdl() + ""));
                tv_month2.setText(BigDecimalUtils.onKeep3Decimal(response.getData().getMonthyxsdl() + ""));
            } else {
                ToastUtils.showShort(response.getMsg());
            }
        } else {
            ToastUtils.showShort("月可售电量获取失败");
        }
    }

    @Override
    public void queryYearSuccess(StoreYearBean response) {
        if (response != null) {
            if (response.getCode() == 200) {
                if (response.getData().getSaleEnergy() == -1) {
                    mTvLeft.setText("不限量");
                } else {
                    mTvLeft.setText(BigDecimalUtils.onKeep3Decimal(response.getData().getSaleEnergy() + ""));
                }
                mTvCenter.setText(response.getData().getYearSaleEnergy() + "");
            } else {
                ToastUtils.showShort(response.getMsg());
            }
        } else {
            ToastUtils.showShort("年可售、已售电量获取失败");
        }
    }

    private void initYearSelecter() {
        //正确设置方式 原因：注意事项有说明
        Calendar nextYear = Calendar.getInstance();;
        Calendar nowYear = Calendar.getInstance();
        nowYear.add(Calendar.MONTH,1);
        nowYear.add(Calendar.YEAR,-1);
        nextYear.add(Calendar.MONTH,1);

        //时间选择器
        pvTimeYear = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                sdf.format(date);
                String year=sdf.format(date);
                year_txt.setText(year);
                mPresenter.queryYear(mBean.getMembersSdId(),year);
            }
        }).setType(new boolean[]{true, false, false, false, false, false})

                .setDecorView((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content))
                .setRangDate(nowYear, nextYear)
                .build();
    }

    private void initMonthSelecter(String sysStartMonth) {
        if (!TextUtils.isEmpty(sysStartMonth)) {
            //正确设置方式 原因：注意事项有说明
            Calendar nextYear = Calendar.getInstance();
//            nextYear.add(Calendar.YEAR, 1);
            nextYear.set(2099,12,1);
            String monthList[] = sysStartMonth.split("-");


            startDate.set(2021, 0, 1);
            //时间选择器
            pvTimeMonth = new TimePickerBuilder(this, new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                    String month=sdf.format(date);
                    month_txt.setText(month);
                    mPresenter.queryMonthEnergy(mBean.getMembersSdId(), month);
                }
            }).setType(new boolean[]{true, true, false, false, false, false})

                    .setDecorView((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content))
                    .setRangDate(startDate, nextYear)
                    .build();
        } else {
            ToastUtils.showShort("初始化月份有误");
        }

    }
}
